/**
 * 2018-3-9 by zhangbo
 */

(function () {
    /*-------------------------
     * 初始化地图组件
     -------------------------*/
    window.viewer = new Cesium.Viewer('cesiumContainer', {
        animation: false, // 是否显示动画控件
        baseLayerPicker: false, // 是否显示图层选择控件
        fullscreenButton: false,
        homeButton: false,
        vrButton: false,
        scene3DOnly: true,
        selectionIndicator: false,
        geocoder: false, // 是否显示地名查找控件
        timeline: false, // 是否显示时间线控件
        sceneModePicker: true, // 是否显示投影方式控件
        navigationHelpButton: false, // 是否显示帮助信息控件
        infoBox: false, // 是否显示点击要素之后显示的信息
//        mapProjection: new Cesium.WebMercatorProjection(Cesium.Ellipsoid.WGS84),
        //skyAtmosphere: false,
        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
            url: "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=5b79423f82f9d691ff2608e24296f617",
            layer: "tdtBasicLayer",
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",
            show: false,
            maximumLevel: 18,
            subdomains: ['t1', 't2', 't3', 't4', 't5']
        }), 
    });

    // The globe must enable lighting to make use of the terrain's vertex normals
//    viewer.scene.globe.enableLighting = true;

    // 去除版权信息
    /**/
    //viewer.scene.fxaa = false
    viewer.scene.camera.constrainedAxis = undefined; // Cartesian3.UNIT_Z;
    //
    viewer.scene.screenSpaceCameraController.zoomEventTypes = [Cesium.CameraEventType.WHEEL, Cesium.CameraEventType.PINCH];
    viewer.scene.screenSpaceCameraController.tiltEventTypes = [Cesium.CameraEventType.PINCH, Cesium.CameraEventType.RIGHT_DRAG];
    viewer._cesiumWidget._creditContainer.style.display = "none";
//	viewer.scene.globe.depthTestAgainstTerrain = true;
    //去掉双击事件
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    viewer.scene.screenSpaceCameraController.maximumZoomDistance = 20000000;
 
    //加入导航条 120.429435003, 31.498404164
    navigationInitialization('cesiumContainer', viewer, {
        homeView: {
            destination: Cesium.Rectangle.fromDegrees(120+23/60+45/3600, 31+30/60+49/3600, 120+27/60+51/3600, 31+28/60+58/3600),
            orientation: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-90),
                roll: 0.0
            }
        },
    });
    //加入选择功能
    //window.cesiumSelect = new CesiumSelect(viewer);
  
    //底图切换
    $(document).on("click", ".base-map-item", function (e) {//底图菜单切换更新按钮图片
        var lastId = $('.base-map-selectedItem').data('id');
        setupBasemap($(this).data('id'), lastId);
        $(".base-map-selectedItem").removeClass("base-map-selectedItem");
        $(this).addClass("base-map-selectedItem");
        $(".btn-base-img").find("img").attr("src", $(this).find("img").attr("src"));
        $(".base-map").slideUp();
        $(".base-map").removeClass("show");
    })

    /**
     * 底图切换
     * @param {String} layerid 当前图层编号
     * @param {String} lastId 上一个选择的图层编号
     */
    function setupBasemap(layerid, lastId) {
        var imageryLayers = viewer.scene.globe.imageryLayers;
        var currentLayer = imageryLayers.get(0);
        if (currentLayer) {
            imageryLayers.remove(currentLayer, false);
        }
        if (lastId === 'tdt-street') {//天地图多删一个标注图层
            var currentLayer = imageryLayers.get(0);
            if (currentLayer) {
                imageryLayers.remove(currentLayer, false);
            }
        }
        switch (layerid) {
            case "default":
                imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                    url: 'google/{z}/s_{x}_{y}_{z}.jpg',
                    tilingScheme: new Cesium.WebMercatorTilingScheme(),
                    maximumLevel: 18
                }), 0);
                break;
            case "bing-imagery":
                imageryLayers.addImageryProvider(new Cesium.BingMapsImageryProvider({
                    url: 'https://dev.virtualearth.net',
                    mapStyle: Cesium.BingMapsStyle.AERIAL
                }), 0);
                break;
            case "bing-imagery-label":
                imageryLayers.addImageryProvider(new Cesium.BingMapsImageryProvider({
                    url: 'https://dev.virtualearth.net',
                    mapStyle: Cesium.BingMapsStyle.AERIAL_WITH_LABELS
                }), 0);
                break;
            case "bing-street":
                imageryLayers.addImageryProvider(new Cesium.BingMapsImageryProvider({
                    url: 'https://dev.virtualearth.net',
                    mapStyle: Cesium.BingMapsStyle.ROAD
                }), 0);
                break;
            case "esri-imagery":
                imageryLayers.addImageryProvider(new Cesium.ArcGisMapServerImageryProvider({
                    url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
                    enablePickFeatures: false
                }), 0);
                break;
            case "esri-street":
                imageryLayers.addImageryProvider(new Cesium.ArcGisMapServerImageryProvider({
                    url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer',
                    enablePickFeatures: false

                }), 0);
                break;
            case "osm-street":
                imageryLayers.addImageryProvider(Cesium.createOpenStreetMapImageryProvider(), 0);
                break;
            case "natural":
                imageryLayers.addImageryProvider(Cesium.createTileMapServiceImageryProvider({
                    url: Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII')
                }), 0);
                break;
            case "tdt-imagery":
                imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
                    url: "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
                    layer: "tdtBasicLayer",
                    style: "default",
                    format: "image/jpeg",
                    tileMatrixSetID: "GoogleMapsCompatible",
                    show: false,
                    maximumLevel: 18,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5']
                }), 0);
                break;
            case "tdt-street":
                imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
                    url: "http://{s}.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
                    layer: "tdtVecBasicLayer",
                    style: "default",
                    format: "image/jpeg",
                    show: false,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5']
                }), 0);
                imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
                    url: "http://{s}.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
                    layer: "tdtAnnoLayer",
                    style: "default",
                    format: "image/jpeg",
                    tileMatrixSetID: "GoogleMapsCompatible",
                    show: false,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5']
                }), 1);
                break;
            default:
        }
    }

      
    /*高级列表区点击事件*/
    $(document).on("click", ".platform-tools", function () {
//        $(".platform-warning,.platform-login-con").removeClass("show");
//        $(".warningInfo,.login-list,.senior-list,#taskList,.task-edit").hide();
        $(".platform-login-con").removeClass("show");
        $(".login-list,.senior-list,#taskList,.task-edit").hide();
        if ($(this).hasClass("show")) {
            $(".tools-list-new").hide();
            $(this).removeClass("show");
            $(".tabBox").hide();
            tabChange('1', 'eagleEye');
            $(".tools-btn").removeClass("tools-act");

        } else {
            $(this).addClass("show");
            $(".tools-list-new").show();
            $(".tabBox,.senior-list").hide();

        }

    });

    /*登录状态区点击事件*/
    $(document).on("click", ".platform-login-con", function () {
//        $(".platform-tools,.platform-warning").removeClass("show");
        $(".platform-tools").removeClass("show");
//        $(".tools-list-new,.tabBox,.senior-list,warningInfo,#taskList,.task-edit").hide();
        $(".tools-list-new,.tabBox,.senior-list,#taskList,.task-edit").hide();
        $(".tools-btn").removeClass("tools-act");
        tabChange('1', 'eagleEye');
        if ($(this).hasClass("show")) {
            $(".login-list").hide();
            $(this).removeClass("show");
        } else {
            $(this).addClass("show");
            $(".login-list").show();
//            $(".tabBox,.senior-list,.warningInfo").hide();
            $(".tabBox,.senior-list").hide();
        }
    });

 

    /*工具列表点击事件*/
    $(document).on("click", ".tools-btn", function () {
        var $this = $(this), curSrc = $this.find(".tools-list-img").attr("src"), curIdx = $this.data("index");
        if (!($this.hasClass("tools-act"))) {
            $(".tools-btn").removeClass("tools-act");
            var toolsBtn = $(".tools-btn");
            for (var i = 0; i < toolsBtn.length; i++) {
                var curSrcL = $(toolsBtn[i]).find(".tools-list-img").attr("src");
                $(toolsBtn[i]).find(".tools-list-img").attr("src", curSrcL.replace("_act", "_nml"));
            }
            $this.addClass("tools-act");
            $this.find(".tools-list-img").attr("src", curSrc.replace("_nml", "_act"));
            btnsClick(curIdx);//展示对应的区域
        } else {
            if (curIdx == "tips") {
                $(".tools-tips").removeClass("tools-act");
                $(".roleMsg").hide();
            } else if (curIdx == "panoVideo") {
                $(".tools-panoVideo").removeClass("tools-act");
                if ($(".list-item-selected").length <= 0 && $(".name-border.selected").length <= 0) {
                    VideoDragLayer.hide();
                } else {
                    $(".changeTab-btn").removeClass("changeTab-btn-selested");
                    $(".airportData").addClass("changeTab-btn-selested").show();
                    $("#sliderAirportData").show();
                    $(".drag_layer").removeClass("videoBar");
                    $("#sliderVideo,.airportVideo").hide();
                    VideoDragLayer.show();
                }
                //VideoDragLayer.hide();
            } else if (curIdx == "common") {
                $(".tools-common").removeClass("tools-act");
                $(".tabBox").hide();
            } else if (curIdx == "senior") {
                $(".senior-list").hide();
                $(".tools-senior").removeClass("tools-act");
            } else if (curIdx == "task") {
                $("#taskList").hide();
                $(".tools-task").removeClass("tools-act");
            }
            $this.find(".tools-list-img").attr("src", curSrc.replace("_act", "_nml"));
        }
    });

//展示对应的区域
    function btnsClick(curIdx) {
        switch (curIdx) {
            case "common":
                //alert("公共工具");
                $(".tabBox").show();
                $(".senior-list,.task-list,.decision-support-list,#taskList").hide();
                tabChange('1', 'eagleEye');
                break;
            case "senior":
                //alert("高级工具");
                $(".tabBox,.decision-support-list,.task-list,#taskList").hide();
                $(".senior-list").show();
                break;
            case "panoVideo":
                //alert("全景视频");
                $(".changeTab-btn").removeClass("changeTab-btn-selested");
                $(".airportVideo").addClass("changeTab-btn-selested").show();
                $(".sliderVideo").show();
                $(".drag_layer").addClass("videoBar");
                $(".sliderAirportData ,.airportData").hide()
                if ($(".list-item-selected").length > 0 || $(".name-border.selected").length > 0) {
                    $(".airportData").show();
                }
                VideoDragLayer.show();
                //playvideo();
                $(".task-list,.tabBox,.decision-support-list").hide();
                //$(".senior-list,.optTabBox,#taskList").hide();
                break;
            case "decision-support":
                //alert("决策支持");
                $(".decision-support-list").show();
                $(".senior-list,.task-list,.tabBox,#taskList,#taskList").hide();
                break;
            case "task":
                //alert("任务管理");
                $("#taskList").show();
                $(".senior-list,.tabBox,.decision-support-list").hide();
                break;
            case "tips":
                //alert("公告信息");
                $(".roleMsg").show();
                break;
            //case "dendrogram":
            //alert("树状图");
            //    $(".tabBox,.senior-list,.optTabBoxt").hide();
            //    break;
            default:
        }
    }

    /*tab切换*/
    $(document).on("click", ".tabBtn", function () {
        var $this = $(this), curId = $this.data("index"), curCl = $this.data("class");
        tabChange(curId, curCl);
    });

    function tabChange(s, k) {
        var h = document.getElementById("tabBox").getElementsByTagName("li");
        for (var i = 1; i <= h.length; i++) {
            if (s == i) {
                if (h[i - 1].className.indexOf(" current") < 0) {
                    h[i - 1].className += " current";
                }
                var tabdiv = document.getElementById("tabcon_" + i);
                $(".tabcon").removeClass("select");
                tabdiv.className = "tabcon select";
                if (h[i - 1].dataset.init === '0') {
                    h[i - 1].dataset.init = '1';
                    window.Events.trigger(Events.ToolTabInitEvent, tabdiv.dataset.index);
                }
                window.Events.trigger(Events.ToolTabActionEvent, tabdiv.dataset.index);
            }
            else {
               // h[i-1].className="tabBtn";
                h[i - 1].className = h[i - 1].className.replace(" current", "");
                //document.getElementById("tabcon_" + i).className = "tabcon";
            }
        }
    }

    //右侧面板专业控制列表    /*高级工具选中和取消*/
    $(document).on("click", ".senior-btn", function () {
        var $this = $(this), curId = $this.data("index"), curCl = $this.data("class");
        if (!$this.hasClass("selected")) {
            $this.addClass("selected");
            addOptTabBtn(curId);//展开该业务所对应的tab按钮
        } else {
            if ((curId == 11) && ($(".senior-btn.selected").find(".btn-flight-ADS-B").length == 1)) {
                $(".changeTab-btn").removeClass("changeTab-btn-selested");
                $(".airportData").addClass("changeTab-btn-selested").show();
                $("#sliderAirportData").show();
                $(".drag_layer").removeClass("videoBar");
                $("#sliderVideo,.airportVideo").hide();
            }
            if ($(".tools-act").data("index") == 'panoVideo') {
                $(".changeTab-btn").removeClass("changeTab-btn-selested");
                $(".airportVideo").addClass("changeTab-btn-selested").show();
                $(".drag_layer").addClass("videoBar");
                $("#sliderAirportData,.airportData").hide();
                $("#sliderVideo").show();
            } else if ($(".tools-act").data("index") == undefined) {
                VideoDragLayer.hide();
            }

            $this.removeClass("selected");

            removeOptTabBtn(curId);//移除该业务所对应的tab按钮
            if ($("#optTabBox").find(".optTabBtn").length <= 0) {
                $(".optTabBtn").removeClass("current");//默认移除所有选中的状态
                $(".optTabcon").removeClass("select");//默认移除所有选中的状态
                $(".optTabBox").hide();//关闭业务操作区域
            }
        }
        if ($("#optTabBox").find(".optTabBtn").length > 0) {
            $(".optTabBox").show();//展开业务操作区域
        }

    });


    //业务内容区关闭按钮事件
    $(document).on("click", ".optTabBox-cal", function () {
        $(".optTabBoxCon").animate({right: "420px"}, 300, function () {
            $(".optTabBoxCon").fadeOut(100);
            $(".optTabcon").removeClass("select");
        });
    });

    //左侧显示移除选中的Tab按钮
    function removeOptTabBtn(m) {
        var optTabBox = document.getElementById('optTabBox'),
            oLists = optTabBox.getElementsByTagName('li');
        optTabBtnList = optTabBox.getElementsByClassName('optTabBtn');
        for (var k = 1; k <= oLists.length; k++) {
            if (k === m) {
                oLists[k-1].className = '';
                document.getElementById("optTabcon_" + (k + 1)).className = "optTabcon";
                //选中展示tab列表的第一个和对应的内容框
                var idx = $($(".optTabBtn")[0]).data("index");
                $(".optTabBtn").removeClass("current");

                if (idx != undefined) {//至少有两个选中的tab时
                    oLists[idx-2].className = 'optTabBtn current';
                    $(".optTabcon").removeClass("select");//默认移除所有选中的状态
                    //document.getElementById("optTabcon_"+(idx)).className="optTabcon select";
                    var tabdiv = document.getElementById("optTabcon_" + (idx));
                    tabdiv.className = "optTabcon select";
                    if (idx != "0") {
                        if (oLists[idx - 2].dataset.init === '0') {
                            oLists[idx - 2].dataset.init = '1';
                            setTimeout(function () {
                                window.Events.trigger(Events.ModuleTabEvent, {
                                    target: tabdiv,
                                    init: true
                                });
                            }, 200);
                        }
                        else {
                            setTimeout(function () {
                                window.Events.trigger(Events.ModuleTabEvent, {
                                    target: tabdiv,
                                    init: false
                                });
                            }, 200);
                        }

                    }
                } else {//只有一个选中的tab时
                    //var tabdivCur = document.getElementById("optTabcon_" + (m+1));
                    //window.Events.trigger(Events.ModuleCloseEvent, tabdivCur.dataset.index);
                }
                var tabdivCur = document.getElementById("optTabcon_" + (m + 1));
                window.Events.trigger(Events.ModuleCloseEvent, tabdivCur.dataset.index);
            }
        }
        //console.log(m + '~+~');
    }

    //左侧面板打开显示操作方法        左侧显示选中的Tab按钮
    function addOptTabBtn(n) {
        $(".optTabBoxCon").animate({right: "10px"}, 600);//固定业务展示的位置
        $(".optTabBoxCon").show();//展开业务内容区
        var optTabBox = document.getElementById('optTabBox'),
            oLists = optTabBox.getElementsByTagName('li');
        for (var k = 1; k <= oLists.length; k++) {
            if (k === n) {
                $(".optTabBtn").removeClass("current");//默认移除所有选中的状态
                oLists[k - 1].className = 'optTabBtn current';
                $(".optTabcon").removeClass("select");//默认移除所有选中的状态

                //document.getElementById("optTabcon_"+(k+1)).className="optTabcon select";
                var tabdiv = document.getElementById("optTabcon_" + (k + 1));
                tabdiv.className = "optTabcon select";
                if (oLists[k-1].dataset.init === '0') {
                    oLists[k-1].dataset.init = '1';
                    setTimeout(function () {
                        window.Events.trigger(Events.ModuleTabEvent, {
                            target: tabdiv,
                            init: true
                        });
                    }, 200);
                }
                else {
                    setTimeout(function () {
                        window.Events.trigger(Events.ModuleTabEvent, {
                            target: tabdiv,
                            init: false
                        });
                    }, 200);
                }
            }
        }
        //console.log(n + '~');
    }

    /*业务Tab操作*/
    $(document).on("click", ".optTabBtn", function () {
        var $this = $(this), curId = $this.data("index"), curCl = $this.data("class");
        $(".optTabBtn").removeClass("current");//默认移除所有选中的状态
        $(".optTabcon").removeClass("select");//默认移除所有选中的状态
        if (curId == '0') {//展示了树状图tab标签
            document.getElementById("optTabBox").getElementsByTagName("li")[0].className = 'optTabBtn current';
            document.getElementById("optTabcon_0").className = "optTabcon select";
            $(".optTabBoxCon").animate({right: "10px"}, 600);//固定业务展示的位置
            $(".optTabBoxCon").show();//展开业务内容区
        } else {
            optTabChange(curId, curCl);
        }

    });

    function optTabChange(s, k) {//tab切换执行函数
        $(".optTabBoxCon").animate({right: "10px"}, 600);//固定业务展示的位置
        $(".optTabBoxCon").show();//展开业务内容区
        var m = document.getElementById("optTabBox").getElementsByTagName("li");
        for (var j = 1; j <= m.length+1; j++) {
            if (s == j) {
                if (m[j-2].className.indexOf(" current") < 0) {
                    m[j-2].className += " current";
                }
//				document.getElementById("optTabcon_"+j).className="optTabcon select";
                var tabdiv = document.getElementById("optTabcon_" + j);
                tabdiv.className = "optTabcon select";
                if (m[j-2].dataset.init === '0') {
                    m[j-2].dataset.init = '1';
//                    window.Events.trigger(Events.ModuleInitEvent, tabdiv);
                    window.Events.trigger(Events.ModuleTabEvent, {target: tabdiv, init: true});
                }
                else {
                    window.Events.trigger(Events.ModuleTabEvent, {target: tabdiv, init: false});
                }
            }
            //else {
            //m[j-1].className = m[j-1].className.replace(" current", "");
            //document.getElementById("optTabcon_" + j).className = "optTabcon";
            //}
        }
    }

    var oDiv = document.getElementById("driveBirds");
    var oList = document.getElementById("driveBirdsList").getElementsByTagName("li");
    var oListCon = document.getElementById("driveBirdsList-con").getElementsByClassName("driveBirds-list");
    //var timer = null;
    document.getElementById("driveBirds").onmouseover = function () {
        for (var i = 0; i < oList.length; i++) {
            oList[i].index = i;
            oList[i].onmouseover = function () {
                change(this.index);
            }
        }
    }
    document.getElementById("driveBirds").onmouseleave = function () {
        for (var j = 0; j < oListCon.length; j++) {
            oListCon[j].className = 'driveBirds-list';
            //console.log("~+~");
        }
    }

    function change(index) {
        //document.getElementById("driveBirdsList-con").style.display = 'block';
        for (var i = 0; i < oList.length; i++) {
            oList[i].className = '';
            oListCon[i].className = 'driveBirds-list';
        }
        oList[index].className = 'cur';
        oListCon[index].className = 'driveBirds-list cur';
    }


    //公共工具窗口关闭
    $(document).on("click", ".comTools-cal", function () {
        $(".tabBox").hide();
        $(".tools-common").removeClass("tools-act");
        var curSrcL = $(".tools-common").find(".tools-list-img").attr("src");
        $(".tools-common").find(".tools-list-img").attr("src", curSrcL.replace("_act", "_nml"));
    });
 

    /*登录人的信息显示和隐藏*/
    $(".platform-login-con").hover(function () {
        $(".show-login-area").fadeIn(300);
    }, function () {
        $(".show-login-area").fadeOut(300);
    });
       
    //跑马灯效果
    var demo = document.getElementById("demo");
    var demo1 = document.getElementById("demo1");
    var demo2 = document.getElementById("demo2");
    demo2.innerHTML = document.getElementById("demo1").innerHTML;

    function Marquee() {
        if (demo.scrollLeft - demo2.offsetWidth >= 0) {
            demo.scrollLeft -= demo1.offsetWidth;
        }
        else {
            demo.scrollLeft++;
        }
    }

    var myvar = setInterval(Marquee, 20);
    demo.onmouseout = function () {
        myvar = setInterval(Marquee, 20);
    }
    demo.onmouseover = function () {
        clearInterval(myvar);
    }

    //跑马灯告警信息弹窗
    $(document).on("click", ".warningBtn", function () {
//        $(".warningInfo").show();
        $(".tools-list-new,#taskList").hide();
    })

    //跑马灯任务管理弹窗
    $(document).on("click", ".taskBtn", function () {
        $("#taskList").show();
//        $(".tools-list-new,.warningInfo").hide();
        $(".tools-list-new").hide();
    })
  
})();